package com.example.basic;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;

public class ProductPagerActivity extends FragmentActivity {
  private ViewPager mViewPager;
  private ArrayList<Product> mProducts;

  public final static String EXTRA_PRODUCT_ID = "com.example.basic.ProductPagerActivity.product_id";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mViewPager = new ViewPager(this);
    mViewPager.setId(R.id.view_pager);
    setContentView(mViewPager);

    Inventory inventory = Inventory.getInstance(this);
    mProducts = inventory.getProducts();

    FragmentManager fm = getSupportFragmentManager();
    mViewPager.setAdapter(new FragmentStatePagerAdapter(fm) {
      @Override
      public int getCount() {
        return mProducts.size();
      }

      @Override
      public Fragment getItem(int pos) {
        Product product = mProducts.get(pos);
        return ProductFragment.newInstance(product.getId());
      }
    });

    // Set the current page from the intent extra
    int productId = getIntent().getIntExtra(EXTRA_PRODUCT_ID, 0);
    for (int i=0; i<mProducts.size(); i++) {
      if (productId == mProducts.get(i).getId()) {
        mViewPager.setCurrentItem(i);
      }
    }
  }
}
